//
//  PlayingVideoViewController.m
//  RunningMan
//
//  Created by dllo on 16/5/20.
//  Copyright © 2016年 JohnnyB. All rights reserved.
//

#define MAS_SHORTHAND
#define MAS_SHORTHAND_GLOBALS

#import "PlayingVideoViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import "ModelOfData.h"
#import "Header.h"
#import "VideoPlayer.h"

@interface PlayingVideoViewController ()

@property (nonatomic, assign) BOOL isPlay;
@property (nonatomic, assign) BOOL isTap;

@property (nonatomic, retain) VideoPlayer *player;
@property (nonatomic, retain) AVPlayerLayer *playerLayer;
@property (nonatomic, retain) AVPlayerItem *playerItem;
@property (nonatomic, retain) UILabel *currentLabel;
@property (nonatomic, retain) UILabel *totalLabel;
@property (nonatomic, retain) UILabel *titleLabel;
@property (nonatomic, retain) UIImageView *playingImageView;
@property (nonatomic, retain) UISlider *progressSlider;
@property (nonatomic, assign) CGFloat totalMovieDuration;//  保存该视频资源的总时长，快进或快退的时候要用
@property (nonatomic, retain) UIButton *playerButton;
@property (nonatomic, retain) UIButton *backButton;
@property (nonatomic, retain) UIView *allView;
@property (nonatomic, assign) id ob;
@end

@implementation PlayingVideoViewController

-(void)dealloc{
    
    [self remove];
    NSLog(@"kkakf");

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    [self addAVPlayer];
    [self addSubView];
    [self addProgressObserver];
    [self addGestureRecognizer];
    [self hideControlsWithDelay:5.0];
    [self addNotificationCenters];
}



-(void)addAVPlayer{
    //创建视频项目对象
    self.playerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:self.modelOfDate.playUrl]];
    
    //创建视频播放器对象
    self.player = [VideoPlayer shareMySelf];
    //创建承载播放器的AVPlayerLayer对象
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    [self.player playWithUrl:self.modelOfDate.playUrl];
    self.playerLayer.frame = CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH);
//  self.playerLayer.frame =  CGRectMake((SCREEN_WIDTH - SCREEN_HEIGHT), (SCREEN_HEIGHT - SCREEN_WIDTH)/2, SCREEN_HEIGHT, SCREEN_WIDTH);

    
    
   
    
    [UIView animateWithDuration:0.3f animations:^{
       
        //    把模拟器向左横转过来 KVO
        if ([UIDevice currentDevice].orientation != UIDeviceOrientationLandscapeLeft) {
            
            NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
            [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
            
        }
    }];
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    
    
    
    
    
    
    
      //将播放器添加到playerView的layer层上
    [self.view.layer addSublayer:self.playerLayer];
    self.player.volume = 1.0f;
    [self.player play];
    
    self.view.userInteractionEnabled = YES;
    
   
    
}


#pragma mark -  添加进度观察 - addProgressObserver
-(void)addProgressObserver{
    
    __block typeof(self) weakSelf = self;
    
    // 该方法返回一个 id类型的值 添加了一个观察者
    _ob = [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        CGFloat duration = CMTimeGetSeconds(weakSelf.playerItem.duration);
        CGFloat current =  CMTimeGetSeconds(weakSelf.player.currentTime);
        
        //        CGFloat rem = duration - current;
        
        NSString *totalTime = [NSString stringWithFormat:@"%02d:%02d", (int)duration/60,(int)duration%60];
        NSString *currentTime = [NSString stringWithFormat:@"%02d:%02d", (int)current/60, (int)current%60];
        //        NSString *timeStr = [NSString stringWithFormat:@"%@/%@", currentTime, totalTime];
        
        weakSelf.currentLabel.text = currentTime;
        weakSelf.totalLabel.text = totalTime;
        
        weakSelf.totalMovieDuration = duration;
        weakSelf.progressSlider.value = current/duration;
        
    }];
    
}

-(void)addSubView{
    
    self.allView  = [UIView new];
    
    [self.view addSubview:self.allView];
    [self.allView makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        
    }];
    self.allView.backgroundColor = [UIColor blackColor];
    self.allView.alpha = 0.3;
    
    //返回按钮
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.backButton.tintColor = [UIColor whiteColor];
    
    self.backButton.frame = CGRectMake(10, 5, 20, 30);
    [self.allView addSubview:self.backButton];
    
    //    [self.backButton makeConstraints:^(MASConstraintMaker *make) {
    //
    //        make.left.offset(20 - (SCREEN_HEIGHT - SCREEN_WIDTH )/2);
    //        make.right.offset(-(SCREEN_HEIGHT - 40));
    //        make.size.offset(CGSizeMake(20, 20));
    //
    //    }];
    [self.backButton setImage:[UIImage imageNamed:@"back@3x.png"] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    //视频标题
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 5, SCREEN_WIDTH - 100, 30)];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.text = self.modelOfDate.title;
    [self.allView addSubview:self.titleLabel];
    
   
    
    
    //当前时间
    self.currentLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, SCREEN_HEIGHT - 30, 60, 20)];
    self.totalLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_HEIGHT   + SCREEN_WIDTH / 3, SCREEN_HEIGHT - 30, 60, 20)];
    
    self.currentLabel.textColor = [UIColor whiteColor];
    self.totalLabel.textColor = [UIColor whiteColor];
    
    [self.allView addSubview:self.currentLabel];
    [self.allView addSubview:self.totalLabel];
    
    
    
    //播放 暂停
    self.playerButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.playerButton.frame = CGRectMake(SCREEN_WIDTH *2/5 , SCREEN_HEIGHT *2/5, SCREEN_WIDTH/6, SCREEN_WIDTH/6);
    NSLog(@"%f", SCREEN_HEIGHT);
    self.playerButton.tintColor = [UIColor whiteColor];
    [self.playerButton setImage:[UIImage imageNamed:@"pause@3x.png"] forState:UIControlStateNormal];
    self.isPlay = YES;
    
    [self.playerButton addTarget:self action:@selector(playOrPuse) forControlEvents:UIControlEventTouchUpInside];
    [self.allView addSubview:self.playerButton];
    
    //进度条
    self.progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(70, SCREEN_HEIGHT - 20, SCREEN_WIDTH - 160, 5)];
    self.progressSlider.minimumValue = 0.0f;
    self.progressSlider.maximumValue = 1.0f;
    
    //改变滑块
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"slider@3x.png"] forState:UIControlStateNormal];
    
    [self.progressSlider addTarget:self action:@selector(sliderAction) forControlEvents:UIControlEventTouchUpInside];
    [self.allView addSubview:self.progressSlider];
    
   
    
}


#pragma mark - addTapGesture
-(void)addGestureRecognizer{
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAllSubViews)];
    [self.view addGestureRecognizer:tap];
    
}

-(void)dismissAllSubViews{
    if (self.isTap == NO) {
        
        [UIView animateWithDuration:1 animations:^{
            self.allView.alpha = 0;
        }];
        
    }else{
        
        [UIView animateWithDuration:1 animations:^{
            self.allView.alpha = 0.5;
            [self hideControlsWithDelay:5.0];
        }];
        
    }
    
    self.isTap = !self.isTap;
    
}

#pragma mark - 观察者 是否播放完毕
-(void)addNotificationCenters{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoPlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    

    
    
}


-(void)videoPlayDidEnd:(NSNotification *)notify{
    
    
    [self dismissViewControllerAnimated:YES completion:^{
        
        [self.player pause];
        
    }];
    
    NSLog(@"播放结束");
}


#pragma mark - play of pause
-(void)playOrPuse{
    
    if (self.isPlay) {
        
        [self.player pause];
        
        //        [self.playerButton setBackgroundImage:[UIImage imageNamed:@"play@3x.png"] forState:UIControlStateNormal];
        [self.playerButton setImage:[UIImage imageNamed:@"play@3x.png"] forState:UIControlStateNormal];
        self.isPlay = NO;
    }else{
        
        [self.player play];
        [self.playerButton setImage:[UIImage imageNamed:@"pause@3x.png"] forState:UIControlStateNormal];
        //        [self.playerButton setBackgroundImage:[UIImage imageNamed:@"pause@3x.png"] forState:UIControlStateNormal];
        
        [self hideControlsWithDelay:3.0];
        self.isPlay = YES;
    }
    
}


#pragma mark - 如果没有tap， 自动隐藏
-(void)hideControlsWithDelay:(NSTimeInterval)delay{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.allView.alpha = 0.0;
            
        }];
        
    });
    
    
}

#pragma mark - back
-(void)backButtonAction{
    
    [self.player pause];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    
}

-(void)sliderAction{
    
    //跳转到时间
    [self.player seekToTime:CMTimeMakeWithSeconds(self.player.currentItem.duration.value/self.player.currentItem.duration.timescale * self.progressSlider.value, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
        [self.player play];
    }];
    
    
}

-(void)remove{
    [self.player removeTimeObserver:_ob];//这个必须写在 [_player release] 之前
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];// 从[NSNotificationCenter defaultCenter] 释放
}

- (void)viewDidDisappear:(BOOL)animated{
//    [self remove];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
